from datetime import datetime
from typing import List
from vnpy.trader.object import BarData, TickData, OrderData, TradeData
from vnpy_ctastrategy.strategies.MyObj import *

from vnpy_ctastrategy import (
    CtaTemplate
)
from time import time
from vnpy_ctastrategy.base import StopOrder

from vnpy_ctastrategy.strategies.myDb import MyTickData,saveMyTickData

from vnpy.trader.database import get_database

class DbTest(CtaTemplate):
    """"""
    author = "Max"

    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):

        self.trackData:List = []

        self.oldVolum=0
        self.old_open_interest=0

        self.data: list = []
        #self.db=mysql_database.MysqlDatabase()
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

    def on_tick(self, tick: TickData):
        # print(f"tick={tick}")
        d: dict = tick.__dict__
        d["last_volume"]=tick.volume-self.oldVolum
        if d['last_volume']!=0:
            d["last_open_interest"]=tick.open_interest-self.old_open_interest
            s=""
            if tick.last_price>=tick.ask_price_1:
                s+="多"
            elif tick.last_price<=tick.bid_price_1:
                s+="空"
            else:
                s+="啥"
            if d["last_open_interest"]>0:
                s+="开"
            elif d["last_open_interest"]<0:
                s+="平"
            else:
                s+="换"
            d["direction"]=s

            print(f"{d['last_volume']},{d['last_open_interest']},{d['direction']}")

            # myTick.last_price=tick.last_price
            # myTick.last_volume=tick.volume-self.oldVolum
            self.oldVolum=tick.volume
            self.old_open_interest=tick.open_interest
            self.data.append(d)
        # print(f"self.data={self.data}")
        if len(self.data)>=10:
            # print(f"save len(self.data)={len(self.data)}")
            saveMyTickData(self,self.data)
            # self.write_log(f"tickList={self.tickList}")
            self.data.clear()
        
    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        pass

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        self.put_event()

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        self.put_event()
        